<!--suppress VueUnrecognizedSlot -->
<!--用户登录-->
<template>
  <div id="userLoginPage">
    <h2 class="title">云图库 - 用户登录</h2>
    <div class="desc">企业级智能协同云图库</div>
    <a-form :model="formState" name="basic" autocomplete="off" @finish="handleSubmit">
      <a-form-item name="userAccount" :rules="[{ required: true, message: '请输入账号' }]">
        <a-input v-model:value="formState.userAccount" placeholder="请输入账号">
          <template #prefix>
            <UserOutlined style="color: rgba(0, 0, 0, 0.25)" />
          </template>
        </a-input>
      </a-form-item>

      <a-form-item
        name="userPassword"
        :rules="[
          { required: true, message: '请输入密码' },
          { min: 8, message: '密码不能小于 8 位' },
        ]"
      >
        <a-input-password v-model:value="formState.userPassword" placeholder="请输入密码">
          <template #prefix>
            <LockOutlined style="color: rgba(0, 0, 0, 0.25)" />
          </template>
        </a-input-password>
      </a-form-item>

      <a-form-item name="captcha" :rules="[{ required: true, message: '请输入验证码' }]">
        <div class="captcha-input">
          <a-input style="width: 65%" v-model:value="formState.captcha" placeholder="请输入验证码">
            <template #prefix>
              <QrcodeOutlined style="color: rgba(0, 0, 0, 0.25)" />
            </template>
          </a-input>
          <img :src="captchaImageUrl" alt="验证码" class="captcha-image" @click="refreshCaptcha" />
        </div>
      </a-form-item>

      <div class="tips">
        没有账号？
        <RouterLink to="/user/register">去注册</RouterLink>
      </div>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 100%" :disabled="loading">
          {{ loading ? '登录中...' : '登录' }}
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { LockOutlined, UserOutlined, QrcodeOutlined } from '@ant-design/icons-vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { getCaptchaUsingGet } from '@/api/captchaController.ts'
import { userLoginUsingPost } from '@/api/userController.ts'
import { message } from 'ant-design-vue'
import { setToken } from '@/utils/auth.ts'

const formState = reactive<API.UserLoginRequest>({
  userAccount: '',
  userPassword: '',
  captcha: '',
})

const router = useRouter()
const loginUserStore = useLoginUserStore()
const loading = ref(false)

const captchaImageUrl = ref('')

// 获取验证码
const refreshCaptcha = async () => {
  try {
    const response = await getCaptchaUsingGet({}, { responseType: 'blob' })
    if (captchaImageUrl.value) {
      URL.revokeObjectURL(captchaImageUrl.value)
    }
    // 将 Blob 转换为 URL
    captchaImageUrl.value = URL.createObjectURL(response.data)
  } catch (error) {
    message.error('获取验证码失败:' + error)
  }
}

/**
 * 表单提交
 * @param values
 */
const handleSubmit = async (values: any) => {
  if (loading.value) return
  loading.value = true
  try {
    const res = await userLoginUsingPost(values)
    //登陆成功，把登录状态保存到全局状态中
    if (res.data.code === 0 && res.data.data) {
      const token = res.data.data.token
      if (!token) {
        console.error('Token is undefined')
      } else {
        setToken(token)
      }
      await loginUserStore.fetchLoginUser()
      message.success('登录成功')
      //跳转到主页
      await router.push({
        path: '/',
        replace: true,
      })
    } else {
      message.error('登录失败 ' + res.data.message)
    }
  } catch (error) {
    message.error('登录失败 ' + error)
    await refreshCaptcha()
    formState.captcha = ''
  } finally {
    loading.value = false
  }
}

// 页面加载时调用 fetchCaptcha
onMounted(() => {
  refreshCaptcha()
})
// 页面卸载时释放 captchaImageUrl
onMounted(() => {
  if (captchaImageUrl.value) {
    URL.revokeObjectURL(captchaImageUrl.value)
  }
})
</script>

<style scoped>
#userLoginPage {
  max-width: 360px;
  margin: 0 auto;
}

.title {
  text-align: center;
  margin-bottom: 16px;
}

.desc {
  text-align: center;
  color: #bbb;
  margin-bottom: 16px;
}

.tips {
  margin-bottom: 16px;
  color: #bbb;
  font-size: 13px;
  text-align: right;
}

.captcha-image {
  margin-bottom: 10px;
  margin-left: 20px;
}
</style>
